//
//  CityDOCatchCrashVC.m
//  TestCrash
//
//  Created by CityDo on 2019/4/22.
//  Copyright © 2019 CityDo. All rights reserved.
//

#import "CityDOCatchCrashVC.h"

@interface CityDOCatchCrashVC ()
    @property (copy,nonatomic)    NSMutableDictionary * _Nullable mutableDict;
    @property (copy,nonatomic)    NSDictionary *relatedDataDict;

    @property (strong, nonatomic) NSString * excepUser;
    @property (strong, nonatomic) NSString * channel;
    @property (strong, nonatomic) NSString * all_disk;//磁盘总空间
    @property (strong, nonatomic) NSString * all_memory;//内存总空间
    @property (strong, nonatomic) NSString * relatedDataKey;
    @property (strong, nonatomic) NSString * relatedDataValue;

@end

@implementation CityDOCatchCrashVC


+ (CityDOCatchCrashVC *)sharedInstance;
{
    static CityDOCatchCrashVC *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[CityDOCatchCrashVC alloc] init];
        CityDOCatchCrash *crashInfo = [[CityDOCatchCrash alloc]init];
        [crashInfo redirectNSLogToDocumentFolder];

    });
    
    return _sharedInstance;
}



- (NSMutableDictionary *)mutableDict
{
    if (!_mutableDict) {
        _mutableDict = [NSMutableDictionary dictionary];
    }
    return _mutableDict;
}

//- (void)viewDidLoad {
//    [super viewDidLoad];
//
//    CityDOCatchCrash *crashInfo = [[CityDOCatchCrash alloc]init];
//    [crashInfo redirectNSLogToDocumentFolder];
//    // Do any additional setup after loading the view.
//}


+ (void)setUserIdentifier:(nonnull NSString *)excepUser;
{
    if (!excepUser) {
        [self sharedInstance].excepUser =  [[UIDevice currentDevice] uuid];
    }else {
         [self sharedInstance].excepUser =  excepUser;
    }
    
}
+ (void)setChannel:(nonnull NSString *)channel;
{
    if (!channel) {
        [self sharedInstance].channel = @"";
    }
    [self sharedInstance].channel = channel;
}
+ (void)relatedDataValue:(nonnull NSString *)value
          relatedDataKey:(nonnull NSString *)key;
{
    if (!key) {
         [self sharedInstance].relatedDataKey = @"";
    } else {
        [self sharedInstance].relatedDataKey = key;
    }
    
    if (!value) {
        [self sharedInstance].relatedDataValue = @"";
    } else {
        [self sharedInstance].relatedDataValue = value;
    }
}

+ (void)postExceptionMessage;
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *logDirectory = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"Log"];
    NSString *logFilePath = [logDirectory stringByAppendingPathComponent:@"UncaughtException.log"];
    NSString *logFilePathOne = [logDirectory stringByAppendingPathComponent:@"UncaughtExceptionAllStackInfo.log"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    
    NSDictionary *infoDictionary=[[NSBundle mainBundle] infoDictionary];
    //     当前应用名称
    NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    NSLog(@"当前应用名称：%@",appCurName);
    
    NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
    NSLog(@"当前应用版本号码：%@",appCurVersionNum);
    //NSString类方法读取内容
    NSString *breakLog = [NSString stringWithContentsOfFile:logFilePath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"NSString类方法读取的内容是：\n%@",breakLog);
    
    NSString *stack = [NSString stringWithContentsOfFile:logFilePathOne encoding:NSUTF8StringEncoding error:nil];
    
    
    NSString *isJailbreak = [NSString stringWithFormat:@"%d", [HelperUtil isJailbreak]];
    if (isJailbreak == nil) {
        isJailbreak = @"";
    }
    
    [formatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *startTime = [formatter stringFromDate:[NSDate date]];
    //    NSLog(@"启动时间-startTime：%@",startTime);
    
    NSString *memory = [HelperUtil getFreeMemoryInfo];
    //    [_mutableDict setValue:_isJailbreak forKey:@"isJailbreak"];
    NSString  *bundleId =[[NSBundle mainBundle] bundleIdentifier];
    NSString *systemVersion  = [[UIDevice currentDevice] systemVersion];
    NSString *deviceModel = [JDDeviceUtils deviceTypeStr];
    NSString *cpuFramework = [HelperUtil getCPUType];
    NSString *deviceId  = [[UIDevice currentDevice] uuid];
    NSString *disk = [HelperUtil freeDiskSpaceInBytes];
    
    
    NSDictionary *stackDict = [HelperUtil dictionaryWithJsonString:stack];
    
    if (stackDict) {
    }
    
    if ( ![self sharedInstance].excepUser) {
        [self sharedInstance].excepUser =  [[UIDevice currentDevice] uuid];
    }
    
    if ( ![self sharedInstance].channel) {
        [self sharedInstance].channel = @"";
    }
    
    if (![self sharedInstance].relatedDataKey) {
        [self sharedInstance].relatedDataKey = @"";
    }
    
    if (![self sharedInstance].relatedDataValue) {
        [self sharedInstance].relatedDataValue = @"";
    }
    
    //三种获取方式
    NSString * oneUUID = [HelperUtil executableUUID];
    NSUUID  *twoUUID =  ExecutableUUID();
    NSUUID *threeUUID =  [HelperUtil ExecutableUUID];
    //    ,@"twoUUID":twoUUID.UUIDString,@"threeUUID":threeUUID.UUIDString
    NSDictionary *dictUUID=@{@"oneUUID":oneUUID,@"twoUUID":twoUUID.UUIDString,@"threeUUID":threeUUID.UUIDString};
    NSString *UUIDStringS = [HelperUtil dataTOjsonString:dictUUID];
    
    NSDictionary *dict=@{@"appName":appCurName,@"stack":oneUUID,@"appVersion":appCurVersionNum,@"isJailbreak":isJailbreak,@"sdkVersion":@"1.0",@"pageTrace":@"开发中",@"startTime":startTime,@"bundleId":bundleId,@"systemVersion":systemVersion,@"deviceModel":deviceModel,@"deviceId":deviceId,@"cpuFramework":cpuFramework,@"channel":@"杭州",@"relatedDataKey": [self sharedInstance].relatedDataKey,@"relatedDataValue":[self sharedInstance].relatedDataValue,@"channel": [self sharedInstance].channel,@"excepUser": [self sharedInstance].excepUser,@"allDisk":[HelperUtil getTotalDiskSpace],@"disk":disk,@"allMemory":[HelperUtil getTotalMemoryInfo],@"memory":memory};
    
    
    [[self sharedInstance].mutableDict addEntriesFromDictionary:stackDict];
    [[self sharedInstance].mutableDict  addEntriesFromDictionary:dict];
    NSDictionary * aa = [self sharedInstance].mutableDict;
    //      NSString *crashStringOne = [ dict descriptionWithLocale:nil];
    //         NSLog(@"crashStringOne = %@",crashStringOne);
    
    [HelperUtil POST:@"http://172.16.16.77:8071/crashmgmt/api/breakinfo/insert" params: aa sucess:^(NSURLSessionDataTask *task, id responseObject) {
        
        [[self sharedInstance] deleteAllStackInfoFile];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
    
    //    NSFileManager *fileManager = [NSFileManager defaultManager];
    //    if (![fileManager fileExistsAtPath:logDirectory]) {
    //        NSError *error = nil;
    //        [fileManager createDirectoryAtPath:logDirectory withIntermediateDirectories:YES attributes:nil error:&error];
    //        if (error) {
    //            NSLog(@"error = %@",[error localizedDescription]);
    //        }
    //    }
    
    //    @"http://172.16.16.77:8180/safe/other/insertBreakLog";
    
    //    NSString *tempURL1 = [CitydoCheckUrlManage sharedManager].otherInsertBreakLog;
    //
    //    NSString *tempURL =@"http://172.16.16.77:8180/safe/other/insertBreakLog";
    //
    //
    //    [CitydoCheckAFAppDotNetAPIClient postAsynchronous:tempURL parameter:dict successBlock:^(NSDictionary *result, NSError *error) {
    //        NSInteger i = [[result objectForKey:@"code"] integerValue];
    //        if ( i==0 ) {
    //            DLog(@"===============崩溃信息上传存成功===============");
    //            [self deleteFile];
    //        } else {
    //            NSLog(@"===============崩溃信息上传存失败===============");
    //            NSLog(@"设备指纹数据保存失败=error  : %@", error.description);
    //        }
    //    } errorBlock:^(NSError *error) {
    //        NSLog(@"===============网络错误===============");
    //    }];
    
}

- (void)deleteUncaughtExceptionFile {
    NSString *logDirectory =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *iOSPath = [logDirectory stringByAppendingPathComponent:@"UncaughtException.log"];
    //UncaughtExceptionAllStackInfo.log
    BOOL isSuccess = [fileManager removeItemAtPath:iOSPath error:nil];
    if (isSuccess) {
        NSLog(@"delete success");
    }else{
        NSLog(@"delete fail");
    }
}

- (void)deleteAllStackInfoFile {
    NSString *logDirectory =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *iOSPath = [logDirectory stringByAppendingPathComponent:@"UncaughtExceptionAllStackInfo.log"];
    BOOL isSuccess = [fileManager removeItemAtPath:iOSPath error:nil];
    if (isSuccess) {
        NSLog(@"delete success");
    }else{
        NSLog(@"delete fail");
    }
}

-(void)deleteFiles {
    [self deleteUncaughtExceptionFile];
    [self deleteAllStackInfoFile];
}

-(NSString *)getDocumentsPath {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *logDirectory = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"Log"];
    
    return logDirectory;
}


@end
